<template>
	<div class="chat-container">
	  <h2>AI 问答助手</h2>
  
	  <!-- 显示所有问答 -->
	  <div class="chat-bubble-container" ref="chatBubbleContainer">
		<div v-for="(qa, index) in qas" :key="index" class="chat-bubble">
		  <div v-if="qa.isQuestion" class="question">
			<p><strong>🙋‍♂️ {{ qa.text }}</strong></p>
		  </div>
		  <div v-if="!qa.isQuestion" class="answer" v-html="getHighlightedAnswer(qa.text)">
		  </div>
		</div>
	  </div>
  
	  <!-- 用户输入框 -->
	  <div class="input-container">
		<input 
		  v-model="userQuestion" 
		  @keyup.enter="sendQuestion" 
		  type="text" 
		  placeholder="请输入你的问题..." 
		  class="input-box" 
		  :disabled="isProcessing"
		/>
		<button @click="sendQuestion" class="submit-btn" :disabled="isProcessing || !userQuestion.trim()">
		  {{ isProcessing ? "思考中..." : "提问" }}
		</button>
	  </div>
	</div>
  </template>
  
  <script>
  import { ref, nextTick, watch } from 'vue';
  import hljs from 'highlight.js'; // 引入 highlight.js
  import 'highlight.js/styles/atom-one-dark.css'; // 你可以选择不同的样式
  
  export default {
	setup() {
	  const qas = ref([]);
	  const userQuestion = ref('');
	  const isProcessing = ref(false);
	  const chatBubbleContainer = ref(null); // 获取容器引用
	  const isUserScrolling = ref(false); // 是否用户手动滚动
	  const scrollThreshold = 50; // 滚动条与底部的距离（单位：px），在此距离内才触发自动滚动
  
	  // 监听滚动事件，判断用户是否手动滚动
	  const handleScroll = () => {
		if (chatBubbleContainer.value) {
		  const { scrollTop, scrollHeight, clientHeight } = chatBubbleContainer.value;
		  // 判断用户是否滚动到接近底部
		  isUserScrolling.value = scrollHeight - scrollTop - clientHeight > scrollThreshold;
		}
	  };
  
	  // 发送问题到后端
	  const sendQuestion = async () => {
		if (!userQuestion.value.trim()) return;
  
		// 添加问题到对话
		qas.value.push({ text: userQuestion.value, isQuestion: true });
		qas.value.push({ text: "", isQuestion: false }); // 预留答案
		const answerIndex = qas.value.length - 1; // 记录答案的位置
  
		isProcessing.value = true;
		const questionEncoded = encodeURIComponent(userQuestion.value); // 对问题进行 URL 编码
		const eventSource = new EventSource(`http://localhost:5011/llm/request?question=${questionEncoded}`);
  
		eventSource.onmessage = (event) => {
		  if (event.data === "done") {
			isProcessing.value = false;
			eventSource.close();
			return;
		  }
  
		  // 逐字显示答案，并处理换行符
		  qas.value[answerIndex].text += event.data.replace(/\\n/g, '<br>');  // 将换行符替换为 <br>
  
		  // 如果用户没有手动滚动，且内容变多时，自动滚动到底部
		  nextTick(() => {
			if (!isUserScrolling.value && chatBubbleContainer.value) {
			  chatBubbleContainer.value.scrollTop = chatBubbleContainer.value.scrollHeight;
			}
		  });
		};
  
		eventSource.onerror = () => {
		  console.error("SSE 连接错误");
		  isProcessing.value = false;
		  eventSource.close();
		};
  
		userQuestion.value = ""; // 清空输入框
	  };
  
	  // 监听容器滚动
	  watch(chatBubbleContainer, (newContainer) => {
		if (newContainer) {
		  newContainer.addEventListener('scroll', handleScroll);
		}
	  });
  
	  // 高亮代码的函数
	  const getHighlightedAnswer = (text) => {
		// 查找代码块并高亮
		const codePattern = /```([\s\S]*?)```/g;
		return text.replace(codePattern, (match, code) => {
		  const highlightedCode = hljs.highlightAuto(code).value; // 高亮代码
		  return `<pre><code class="hljs">${highlightedCode}</code></pre>`; // 返回高亮后的代码块
		});
	  };
  
	  return { qas, userQuestion, isProcessing, sendQuestion, chatBubbleContainer, getHighlightedAnswer };
	}
  };
  </script>
  
  <style scoped>
  .chat-container {
	max-width: 900px;
	margin: 0 auto;
	height: 400px;
	padding: 20px;
	font-family: Arial, sans-serif;
  }
  
  .chat-bubble-container {
	display: flex;
	flex-direction: column;
	height: 400px; /* 设置合适的高度 */
	overflow-y: auto; /* 启用垂直滚动条 */
	margin-bottom: 20px;
	background-color: #f1f1f1;
  }
  
  .chat-bubble {
	margin-bottom: 10px;
  }
  .chat-bubble:nth-of-type(2n-1) {
	width: auto;
	display: flex;
	justify-content: flex-end;
  }
  .chat-bubble:nth-of-type(2n) {
	width: 400px;
  }
  .question {
	display: inline-block;
	background-color: #dff0d8;
	padding: 10px;
	border-radius: 5px;
	margin: 10px;
  }
  
  .answer {
	margin: 10px;
	background-color: #8783643e;
	padding: 10px;
	border-radius: 5px;
	white-space: pre-wrap; /* 保证换行符能生效 */
	word-wrap: break-word; /* 防止长单词撑开容器 */
  }
  
  .input-container {
	display: flex;
	margin-top: 20px;
  }
  
  .input-box {
	flex: 1;
	padding: 10px;
	font-size: 16px;
	border-radius: 5px;
	border: 1px solid #ccc;
  }
  
  .submit-btn {
	padding: 10px 15px;
	font-size: 16px;
	background-color: #4CAF50;
	color: white;
	border: none;
	border-radius: 5px;
	cursor: pointer;
  }
  
  .submit-btn:hover {
	background-color: #45a049;
  }
  
  .submit-btn:disabled {
	background-color: #ccc;
	cursor: not-allowed;
  }
  </style>
  